package com.authine.cloudpivot.ext.service.impl;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.security.crypto.factory.PasswordEncoderFactories;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.authine.cloudpivot.engine.enums.type.GenderType;
import com.authine.cloudpivot.ext.constant.UserConstants;
import com.authine.cloudpivot.ext.domain.OrgDepartment;
import com.authine.cloudpivot.ext.domain.OrgDeptUser;
import com.authine.cloudpivot.ext.domain.OrgRoleUser;
import com.authine.cloudpivot.ext.domain.OrgUser;
import com.authine.cloudpivot.ext.mapper.OrgDepartmentMapper;
import com.authine.cloudpivot.ext.mapper.OrgDeptUserMapper;
import com.authine.cloudpivot.ext.mapper.OrgRoleUserMapper;
import com.authine.cloudpivot.ext.mapper.OrgUserMapper;
import com.authine.cloudpivot.ext.service.IZzdEventCallbackService;
import com.authine.cloudpivot.ext.service.IZzdOrgApiService;
import com.authine.cloudpivot.util.StringUtil;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;

/**
 * 专有钉事件回调事件处理业务实现类
 * 
 * @author shinka
 * @date 2021/07/13
 */
@Service
public class ZzdEventCallbackServiceImpl implements IZzdEventCallbackService {

    private static Logger log = LoggerFactory.getLogger(ZzdEventCallbackServiceImpl.class);

    @Value("${syncorg.notify.corpId}")
    private String corpId;

    @Autowired
    private IZzdOrgApiService zzdOrgApiService;
    @Autowired
    private OrgUserMapper orgUserMapper;
    @Autowired
    private OrgDeptUserMapper orgDeptUserMapper;
    @Autowired
    private OrgRoleUserMapper orgRoleUserMapper;
    @Autowired
    private OrgDepartmentMapper orgDepartmentMapper;

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void addOrUpdateOrg(Map<String, Object> params) {
        log.debug("[组织增量回调-开始]::addOrUpdateOrg: params = {}", params);

        JSONObject contentJson = JSONObject.fromObject(params);
        JSONArray organizationCodes = contentJson.getJSONArray("organizationCodes");
        String tenantId = contentJson.getString("tenantId");

        try {
            for (int i = 0; i < organizationCodes.size(); i++) {
                String organizationCode = organizationCodes.getString(i);
                // 获取部门详情
                Map<String, String> apiParams = new HashMap<>();
                apiParams.put("organizationCode", organizationCode);
                apiParams.put("tenantId", tenantId);
                String apiResult = zzdOrgApiService.getOrganizationByCode(apiParams);
                log.debug("getOrganizationByCode apiResult={}", apiResult);
                JSONObject json = JSONObject.fromObject(apiResult);
                if (!json.getBoolean("success")) {
                    log.error("获取部门详情失败，apiResult={}", apiResult);
                    break;
                }
                JSONObject content = json.getJSONObject("content");
                JSONObject organization = content.getJSONObject("data");
                if (null == organization) {
                    log.error("专有钉获取部门详情失败，部门ID={}", organizationCode);
                    break;
                }
                String parentDeptId = organization.getString("parentCode");

                OrgDepartment orgDept = new OrgDepartment();
                orgDept.setCorpId(corpId);
                orgDept.setId(organizationCode);
                orgDept.setSourceId(organizationCode);
                orgDept.setParentId(parentDeptId);
                orgDept.setSortKey(organization.getLong("displayOrder"));
                orgDept.setName(organization.getString("organizationName"));
                orgDept.setLeaf(organization.getBoolean("leaf"));
                orgDept.setCreatedTime(new Date());
                orgDept.setModifiedTime(new Date());
                orgDept.setModifier(UserConstants.USERID_ADMIN);
                orgDept.setIsShow(true);
                orgDept.setDeptType(UserConstants.DEPT_TYPE);
                if ("A".equals(organization.getString("status"))) {
                    orgDept.setDeleted(false);
                    orgDept.setEnabled(true);
                } else {
                    orgDept.setDeleted(true);
                    orgDept.setEnabled(false);
                }

                // 查询部门是否已存在，更新/新增部门
                OrgDepartment dbDeptment = orgDepartmentMapper.selectOneByPrimaryKey(organizationCode);
                if (null != dbDeptment) {
                    String dbParentDeptId = dbDeptment.getParentId();
                    if (parentDeptId.equals(dbParentDeptId)) {
                        log.debug("更新部门信息，部门parentId无变化，parentId={}", parentDeptId);
                        orgDept.setQueryCode(dbDeptment.getQueryCode());
                        Integer res = orgDepartmentMapper.updateByDepartment(orgDept);
                        log.debug("更新部门信息，部门parentId无变化，result={}", res);
                    } else {
                        log.debug("更新部门信息，部门parentId变更，parentId={}", parentDeptId);
                        // 先更新当前部门，dbParentDeptment=新的父部门
                        OrgDepartment dbParentDeptment = orgDepartmentMapper.selectOneByPrimaryKey(parentDeptId);
                        if (null == dbParentDeptment) {
                            log.error("更新部门信息，部门parentId变更，result={}", "要更新的部门不存在");
                            break;
                        }
                        String queryCode = dbParentDeptment.getQueryCode() + "#" + organizationCode;
                        orgDept.setQueryCode(queryCode);
                        Integer res = orgDepartmentMapper.updateByDepartment(orgDept);
                        log.debug("更新部门信息，部门parentId变更，result={}", res);
                        // 刷新部门及子部门queryCode，同步的时候sourceId和deptId保存的是一样的
                        updateChildQueryCodeByParent(queryCode, organizationCode, organizationCode);
                        // 更新变更后的上级部门叶子节点
                        if (dbParentDeptment.getLeaf()) {
                            dbParentDeptment.setLeaf(false);
                            Integer res1 = orgDepartmentMapper.updateByDepartment(dbParentDeptment);
                            log.debug("更新部门信息，部门parentId变更，更新调整后父部门叶子节点，result={}", res1);
                        }
                        // 原上级部门如果没有子部门，则更新叶子节点
                        List<OrgDepartment> childDeptList = orgDepartmentMapper.selectDeptByParentId(dbParentDeptId);
                        // 事务下数据没有提交，前面的修改没生效，因此会查出来一条当前子部门数据
                        if (CollectionUtils.isEmpty(childDeptList)) {
                            // 调整前的父部门
                            OrgDepartment historyDbParentDeptment =
                                orgDepartmentMapper.selectOneByPrimaryKey(dbParentDeptId);
                            if (null == historyDbParentDeptment) {
                                log.error("更新部门信息，部门parentId变更，更新调整前父部门叶子节点，result={}", "查询修改前父部门，父部门不存在");
                                break;
                            }
                            historyDbParentDeptment.setLeaf(true);
                            Integer res2 = orgDepartmentMapper.updateByDepartment(historyDbParentDeptment);
                            log.debug("更新部门信息，部门parentId变更，更新调整前父部门叶子节点，result={}", res2);
                        }
                    }
                } else {
                    // 查上级部门
                    OrgDepartment dbParentDeptment = orgDepartmentMapper.selectOneByPrimaryKey(parentDeptId);
                    if (null == dbParentDeptment) {
                        // 不可能添加跟部门，该场景不考虑
                        log.error("添加新部门，上级部门不存在，parentId={}", parentDeptId);
                        break;
                    }
                    orgDept.setQueryCode(dbParentDeptment.getQueryCode() + "#" + organizationCode);
                    Integer res = orgDepartmentMapper.insertByDepartment(orgDept);
                    log.debug("添加新部门，result={}", res);
                    // 更新上级部门叶子节点
                    if (dbParentDeptment.getLeaf()) {
                        dbParentDeptment.setLeaf(false);
                        Integer res1 = orgDepartmentMapper.updateByDepartment(dbParentDeptment);
                        log.debug("添加新部门-更新父部门叶子节点，result={}", res1);
                    }
                }
            }
        } catch (Exception e) {
            log.error("[组织增量回调-结束]::addOrUpdateOrg: 异常信息：exception={}", e.toString());
            e.printStackTrace();
        }
        log.debug("[组织增量回调-结束]::addOrUpdateOrg: end");
    }

    @Override
    public void modifyParentOrg(Map<String, Object> params) {
        log.debug("[组织增量回调-开始]::modifyParentOrg: params = {}", params);
        // 部门父组织变更相当于当前部门信息变更，也会走addOrUpdateOrg，因此这个事件不处理，放在addOrUpdateOrg内实现
        log.debug("[组织增量回调-结束]::modifyParentOrg: end");
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void deleteOrg(Map<String, Object> params) {
        log.debug("[组织增量回调-开始]::deleteOrg: params = {}", params);

        try {
            JSONObject contentJson = JSONObject.fromObject(params);
            JSONArray organizationCodes = contentJson.getJSONArray("organizationCodes");
            // String tenantId = contentJson.getString("tenantId");
            for (int i = 0; i < organizationCodes.size(); i++) {
                String organizationCode = organizationCodes.getString(i);
                // 先查询部门是否存在
                OrgDepartment dbDeptment = orgDepartmentMapper.selectOneByPrimaryKey(organizationCode);
                if (null == dbDeptment) {
                    log.error("deleteOrg 删除部门，未查询到部门，请先同步组织以保证数据正确性。");
                    return;
                }
                OrgDepartment orgDept = new OrgDepartment();
                orgDept.setDeleted(true);
                orgDept.setEnabled(false);
                orgDept.setName(dbDeptment.getName());
                orgDept.setParentId(dbDeptment.getParentId());
                orgDept.setQueryCode(dbDeptment.getQueryCode());
                orgDept.setLeaf(dbDeptment.getLeaf());
                orgDept.setModifier(UserConstants.USERID_ADMIN);
                orgDept.setModifiedTime(new Date());
                orgDept.setId(organizationCode);

                Integer res = orgDepartmentMapper.updateByDepartment(orgDept);
                log.debug("[删除部门，更新部门状态，result={}", res);
                /*// 父部门下面如果没有子部门则更新叶子节点
                String parentDeptId = dbDeptment.getParentId();
                List<OrgDepartment> childDeptList = orgDepartmentMapper.selectDeptByParentId(parentDeptId);
                // 事务下数据没有提交，前面的修改没生效，因此会查出来一条当前子部门数据
                if (CollectionUtils.isEmpty(childDeptList)) {
                    // 调整前的父部门
                    OrgDepartment parentDeptment = orgDepartmentMapper.selectOneByPrimaryKey(parentDeptId);
                    if (null == parentDeptment) {
                        log.error("删除部门，修改父部门叶子节点，result={}", "查询父部门为空");
                        return;
                    }
                    parentDeptment.setLeaf(true);
                    Integer res2 = orgDepartmentMapper.updateByDepartment(parentDeptment);
                    log.debug("删除部门，更新父部门叶子节点，result={}", res2);
                }
                */
                // 删除用户
                Integer res1 = orgDeptUserMapper.deleteByDeptId(organizationCode);
                log.debug("[删除部门，删除部门用户，result={}", res1);
                Integer res2 = orgRoleUserMapper.deleteByDeptId(organizationCode);
                log.debug("[删除部门，删除角色用户，result={}", res2);
                Integer res3 = orgUserMapper.deleteLogicByDepartmentId(organizationCode);
                log.debug("[删除部门，删除用户，result={}", res3);
            }
        } catch (Exception e) {
            log.error("[组织增量回调-结束]::deleteOrg: 异常信息：exception={}", e.toString());
            e.printStackTrace();
        }
        log.debug("[组织增量回调-结束]::deleteOrg: end");
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void addOrUpdateUser(Map<String, Object> params) {
        log.debug("[组织增量回调-开始]::addOrUpdateUser: params = {}", params);

        JSONObject contentJson = JSONObject.fromObject(params);
        String accountId = contentJson.getString("accountId");
        String tenantId = contentJson.getString("tenantId");
        JSONArray employeeCodes = contentJson.getJSONArray("employeeCodes");
        // 只会有一个
        String employeeCode = String.valueOf(employeeCodes.get(0));

        // 获取用户详情
        OrgUser orgUser = handleOrgUser(employeeCode, tenantId);
        if (null == orgUser) {
            log.error("[组织增量回调-结束]::addOrUpdateUser: orgUser is null.");
            return;
        }
        orgUser.setUserId(accountId);
        orgUser.setUsername(accountId);
        orgUser.setSourceId(accountId);

        String[] departmentIds = orgUser.getDepartmentId().split(",");
        orgUser.setDepartmentId(departmentIds[0]);
        String[] roleCodes = orgUser.getExtend1().split(",");
        orgUser.setExtend1(null);

        log.debug("addOrUpdateUser handleOrgUser orgUser={}", orgUser);

        // 员工信息获取成功，根据用户id查询用户表确定是新增还是更新
        try {
            String orgDeptUserId = orgUser.getId();
            List<OrgUser> orgUserList = orgUserMapper.selectByUserId(orgUser);
            if (CollectionUtils.isEmpty(orgUserList)) {
                orgUserMapper.insertByUser(orgUser);
            } else {
                if (orgUserList.size() > 1) {
                    throw new Exception("orgUser重复，id=" + orgDeptUserId);
                }
                orgDeptUserId = orgUserList.get(0).getId();
                orgUserMapper.updateByUser(orgUser);
            }

            // 变更后部门可能不一致，先删除再新增
            Integer res0 = orgDeptUserMapper.deleteByUserId(orgDeptUserId);
            log.debug("部门用户变更，用户多部门删除，res=", res0);
            // 更新部门表
            for (int i = 0; i < departmentIds.length; i++) {
                // 获取用户和部门关系
                if (UserConstants.USER_ENABLE.equals(orgUser.getStatus())) {
                    String deptId = departmentIds[i];
                    if (StringUtils.isNotBlank(deptId)) {
                        log.debug("addOrUpdateUser insertByDeptUser deptId={}, orgDeptUserId={}, orgUser={}", deptId,
                            orgDeptUserId, orgUser);
                        insertByDeptUser(deptId, orgDeptUserId, orgUser);
                    }
                }
            }

            // 写入角色表，先刪除
            Integer res1 = orgRoleUserMapper.deleteByUserId(orgDeptUserId);
            log.debug("角色用户变更，角色用户删除，res=", res1);
            for (int i = 0; i < roleCodes.length; i++) {
                // 获取用户和部门关系
                if (UserConstants.USER_ENABLE.equals(orgUser.getStatus())) {
                    String roleCode = roleCodes[i];
                    if (StringUtils.isNotBlank(roleCode)) {
                        log.debug("addOrUpdateUser insertByRoleUser roleCode={}, orgDeptUserId={}, orgUser={}",
                            roleCode, orgDeptUserId, orgUser);
                        insertByRoleUser(roleCode, orgDeptUserId, orgUser);
                    }
                }
            }
        } catch (Exception e) {
            log.error("[组织增量回调-结束]::addOrUpdateUser: 更新数据库相关逻辑异常，exception={}", e.toString());
            e.printStackTrace();
        }
        log.debug("[组织增量回调-结束]::addOrUpdateUser: end");
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void deleteUser(Map<String, Object> params) {
        log.debug("[组织增量回调-开始]::deleteUser: params = {}", params);

        try {
            JSONObject contentJson = JSONObject.fromObject(params);
            JSONArray infos = contentJson.getJSONArray("infos");
            for (int i = 0; i < infos.size(); i++) {
                String accountId = contentJson.getString("accountId");
                // 查询用户是否存在
                OrgUser orgUser = new OrgUser();
                orgUser.setUserId(accountId);
                List<OrgUser> orgUserList = orgUserMapper.selectByUserId(orgUser);
                if (CollectionUtils.isEmpty(orgUserList)) {
                    log.error("deleteUser orgUser不存在，userId={}", accountId);
                    break;
                } else {
                    if (orgUserList.size() > 1) {
                        log.error("deleteUser orgUser重复，userId=" + accountId);
                        break;
                    }
                    // 用户
                    OrgUser updateOrgUser = orgUserList.get(0);
                    String userId = updateOrgUser.getId();
                    updateOrgUser.setEnabled(false);
                    updateOrgUser.setDeleted(true);
                    Integer res0 = orgUserMapper.updateByUser(updateOrgUser);
                    log.debug("deleteUser，更新用户可用状态，userId={}，res=", userId, res0);
                    // 部门用户
                    Integer res1 = orgDeptUserMapper.deleteByUserId(userId);
                    log.debug("deleteUser，部门用户删除，userId={}，res=", userId, res1);
                    // 角色用户
                    Integer res2 = orgRoleUserMapper.deleteByUserId(userId);
                    log.debug("deleteUser，角色用户删除，res=", res2);
                }
            }
        } catch (Exception e) {
            log.error("[组织增量回调-结束]::deleteUser: 业务逻辑处理异常，exception={}", e.toString());
            e.printStackTrace();
        }
        log.debug("[组织增量回调-结束]::deleteUser: end");
    }

    @Override
    public void orgRelatedUser(Map<String, Object> params) {
        log.debug("[组织增量回调-开始]::orgRelatedUser: params = {}", params);
        log.debug("[组织增量回调-结束]::orgRelatedUser: end");
    }

    @Override
    public void orgCancelRelatedUser(Map<String, Object> params) {
        log.debug("[组织增量回调-开始]::orgCancelRelatedUser: params = {}", params);
        // 删除实际上走取
        deleteUser(params);
        log.debug("[组织增量回调-结束]::orgCancelRelatedUser: end");
    }

    private OrgUser handleOrgUser(String employeeCode, String tenantId) {
        if (StringUtils.isBlank(employeeCode) || StringUtils.isBlank(tenantId)) {
            log.error("handleOrgUser employeeCode or tenantId is null.");
            return null;
        }
        try {
            Map<String, String> apiParams = new HashMap<>();
            apiParams.put("employeeCode", employeeCode);
            apiParams.put("tenantId", tenantId);

            // 获取用户详情
            String apiResult = zzdOrgApiService.getEmployeeByCode(apiParams);
            log.debug("getEmployeeByCode apiResult={}", apiResult);
            JSONObject json = JSONObject.fromObject(apiResult);
            if (!json.getBoolean("success")) {
                throw new Exception(apiResult);
            }
            JSONObject content = json.getJSONObject("content");
            // 人员信息
            JSONObject employee = content.getJSONObject("data");
            // 获取用户任职（部门相关信息）
            apiParams.put("employeePositionType", "EMPLOYEE_POSITION_ALL");
            String apiResult2 = zzdOrgApiService.listEmployeePositionsByEmployeeCode(apiParams);
            log.debug("listEmployeePositionsByEmployeeCode apiResult={}", apiResult2);
            JSONObject json2 = JSONObject.fromObject(apiResult2);
            if (!json2.getBoolean("success")) {
                throw new Exception(apiResult2);
            }
            JSONObject content2 = json2.getJSONObject("content");
            // 任职信息（部门）
            JSONArray employeePositions = content2.getJSONArray("data");
            return buildOrgUser(employee, employeePositions);
        } catch (Exception e) {
            log.error("handleOrgUser has an exception. exception={}", e.toString());
            e.printStackTrace();
        }
        return null;
    }

    private OrgUser buildOrgUser(JSONObject employee, JSONArray employeePositions) throws ParseException {
        if (employee.isEmpty()) {
            log.error("buildOrgUser employee is null.");
            return null;
        }

        Date thisDate = new Date();
        String password =
            PasswordEncoderFactories.createDelegatingPasswordEncoder().encode(UserConstants.USER_PASSWORD);

        OrgUser orgUser = new OrgUser();
        orgUser.setId(StringUtil.getUUID());
        orgUser.setCreater(UserConstants.USERID_ADMIN);
        orgUser.setModifier(UserConstants.USERID_ADMIN);
        orgUser.setModifiedTime(thisDate);
        orgUser.setActive(true);
        orgUser.setAdmin(false);
        orgUser.setGender(GenderType.OTHER.toString());
        orgUser.setLeader(false);
        orgUser.setPassword(password);
        orgUser.setDeleted(false);
        orgUser.setExtend2("jobNumber:");
        orgUser.setEnabled(true);
        orgUser.setCorpId(corpId);

        Date gmtCreate = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").parse(employee.getString("gmtCreate"));
        String status = employee.getString("status");
        int empGender = employee.getInt("empGender");
        String name = employee.getString("employeeName");

        orgUser.setName(name);
        orgUser.setCreatedTime(gmtCreate);
        orgUser.setExtend1(employee.getString("empJobLevelCode"));
        orgUser.setExtend2(employee.getString("empBudgetedPostCode"));
        orgUser.setExtend3(employee.getString("gmtCreate"));
        // 性别
        if (UserConstants.INT_1 == empGender) {
            orgUser.setGender(GenderType.MALE.toString());
        } else if (UserConstants.INT_2 == empGender) {
            orgUser.setGender(GenderType.FEMALE.toString());
        }
        // 状态
        if ("A".equals(status)) {
            orgUser.setStatus(UserConstants.USER_ENABLE);
        } else {
            orgUser.setStatus(UserConstants.USER_DISABLE);
        }
        // 姓名转拼音
        orgUser.setPinYin(name == null ? null : StringUtil.getPinyinLowCase(name));
        orgUser.setShortPinYin(name == null ? null : StringUtil.getPinYinHeadCharLowCase(name));

        // 用户部门
        StringBuilder sbOrganizationCode = new StringBuilder();
        StringBuilder sbEmpPosEmployeeRoleCode = new StringBuilder();
        for (int i = 0; i < employeePositions.size(); i++) {
            JSONObject position = employeePositions.getJSONObject(i);
            boolean mainJob = position.getBoolean("mainJob");
            String positionStatus = position.getString("status");
            String organizationCode = position.getString("organizationCode");
            String empPosEmployeeRoleCode = position.getString("empPosEmployeeRoleCode");
            if ("A".equals(positionStatus)) {
                if (mainJob) {
                    sbOrganizationCode.insert(0, ",").insert(0, organizationCode);
                    sbEmpPosEmployeeRoleCode.insert(0, ",").insert(0, empPosEmployeeRoleCode);
                } else {
                    sbOrganizationCode.append(organizationCode).append(",");
                    sbEmpPosEmployeeRoleCode.append(empPosEmployeeRoleCode).append(",");
                }
            }
        }
        if (sbOrganizationCode.indexOf(",") != -1) {
            sbOrganizationCode.deleteCharAt(sbOrganizationCode.length() - 1);
        }
        if (sbEmpPosEmployeeRoleCode.indexOf(",") != -1) {
            sbEmpPosEmployeeRoleCode.deleteCharAt(sbEmpPosEmployeeRoleCode.length() - 1);
        }
        orgUser.setDepartmentId(sbOrganizationCode.toString());
        orgUser.setExtend1(sbEmpPosEmployeeRoleCode.toString());
        return orgUser;
    }

    private void insertByDeptUser(String deptId, String orgDeptUserId, OrgUser orgUser) {
        OrgDeptUser orgDeptUser = new OrgDeptUser();
        orgDeptUser.setId(StringUtil.getUUID());
        orgDeptUser.setUserId(orgDeptUserId);
        orgDeptUser.setDeptId(deptId);
        orgDeptUser.setCreater(UserConstants.USERID_ADMIN);
        orgDeptUser.setCreatedTime(orgUser.getCreatedTime());
        orgDeptUser.setModifier(UserConstants.USERID_ADMIN);
        orgDeptUser.setModifiedTime(orgUser.getModifiedTime());
        orgDeptUser.setExtend3(orgUser.getExtend3());
        orgDeptUser.setDeleted(false);
        orgDeptUser.setMain(false);

        Integer res = orgDeptUserMapper.insertByDeptUser(orgDeptUser);
        log.debug("[insertByDeptUser，新增部门用户，result={}", res);
    }

    private void insertByRoleUser(String roleCode, String orgDeptUserId, OrgUser orgUser) {
        OrgRoleUser orgRoleUser = new OrgRoleUser();
        orgRoleUser.setId(StringUtil.getUUID());
        orgRoleUser.setUserId(orgDeptUserId);
        orgRoleUser.setRoleId(roleCode);
        orgRoleUser.setCreater(UserConstants.USERID_ADMIN);
        orgRoleUser.setCreatedTime(orgUser.getCreatedTime());
        orgRoleUser.setModifier(UserConstants.USERID_ADMIN);
        orgRoleUser.setModifiedTime(orgUser.getModifiedTime());
        orgRoleUser.setExtend3(orgUser.getExtend3());
        orgRoleUser.setDeleted(false);
        orgRoleUser.setUnitType(UserConstants.UNIT_TYPE);

        Integer res = orgRoleUserMapper.insertByRoleUser(orgRoleUser);
        log.debug("[insertByRoleUser，插入角色用户，result={}", res);
    }

    /**
     * 
     * @param parentId
     *            父部门的id，即子部门parentId
     * @param sourceId
     *            父部门sourceId
     * @param queryCode
     *            父部门queryCode
     * 
     */
    private void updateChildQueryCodeByParent(String queryCode, String parentId, String sourceId) {
        // 查询子部门
        try {
            List<OrgDepartment> childDeptList = orgDepartmentMapper.selectDeptByParentId(parentId);
            if (CollectionUtils.isEmpty(childDeptList)) {
                log.debug("组织增量回调事件，刷新queryCode，查询子部门数据为空");
                return;
            }
            for (int i = 0; i < childDeptList.size(); i++) {
                OrgDepartment childDept = childDeptList.get(i);
                String childDeptId = childDept.getId();
                String childSourceId = childDept.getSourceId();
                String childQueryCode = queryCode + "#" + childDept.getQueryCode();

                OrgDepartment upateDept = new OrgDepartment();
                upateDept.setId(childDeptId);
                upateDept.setQueryCode(childQueryCode);
                Integer res = orgDepartmentMapper.updateQueryCode(upateDept);
                log.debug("更新queryCode，res={}，更新前：deptId={},queryCode={}，更新后：deptId={},queryCode={}", res, childDeptId,
                    queryCode, childDeptId, childQueryCode);
                // 递归
                updateChildQueryCodeByParent(childQueryCode, childDeptId, childSourceId);
            }
        } catch (Exception e) {
            log.error("组织增量回调事件，刷新queryCode，异常信息={}", e.toString());
        }

    }

}
